package org.example.aienglishapp.controller.article;

import org.example.aienglishapp.entity.article.Favorite;
import org.example.aienglishapp.service.article.FavoriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {

    private static final Logger logger = LoggerFactory.getLogger(FavoriteController.class);

    @Autowired
    private FavoriteService favoriteService;

    // 添加收藏
    @PostMapping("/add")
    public ResponseEntity<String> addFavorite(@RequestParam Long userId, @RequestParam Long articleId) {
        try {
            // 确认请求参数
            logger.info("Received userId: {}, articleId: {}", userId, articleId);

            // 执行收藏操作
            favoriteService.addFavorite(userId, articleId);

            // 返回成功响应
            return ResponseEntity.ok("文章已添加到收藏");
        } catch (Exception e) {
            logger.error("Error adding favorite: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("收藏失败");
        }
    }

    // 删除收藏
    @DeleteMapping("/remove")
    public ResponseEntity<String> removeFavorite(@RequestParam Long userId, @RequestParam Long articleId) {
        try {
            // 执行删除收藏操作
            favoriteService.removeFavorite(userId, articleId);
            return ResponseEntity.ok("收藏已删除");
        } catch (Exception e) {
            logger.error("Error removing favorite: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("删除失败");
        }
    }

    // 获取用户的所有收藏
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getAllFavoritesByUserId(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从缓存中获取收藏列表
            List<Favorite> favorites = favoriteService.getAllFavoritesByUserId(userId);

            // 如果缓存中没有数据，则从数据库查询并更新缓存
            if (favorites != null && !favorites.isEmpty()) {
                response.put("data", favorites);
            } else {
                response.put("data", new ArrayList<>());
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error fetching favorites for userId: {}", userId, e);
            response.put("error", "服务器内部错误");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 检查收藏状态
    @GetMapping("/check")
    public ResponseEntity<Map<String, Object>> checkFavorite(@RequestParam Long userId, @RequestParam Long articleId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查是否已经收藏，优先从Redis缓存中获取
            boolean isFavorited = favoriteService.isFavorited(userId, articleId);

            // 返回结果
            response.put("isFavorited", isFavorited);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error checking favorite status for userId: {}, articleId: {}", userId, articleId, e);
            response.put("error", "服务器内部错误");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 根据收藏 ID 获取收藏
    @GetMapping("/{favoriteId}")
    public ResponseEntity<Favorite> getFavoriteById(@PathVariable Long favoriteId) {
        try {
            Favorite favorite = favoriteService.getFavoriteById(favoriteId);
            return ResponseEntity.ok(favorite);
        } catch (Exception e) {
            logger.error("Error fetching favorite by ID: {}", favoriteId, e);
            return ResponseEntity.status(500).body(null);
        }
    }
}